<template>
  <div class="note-sidebar">
    <div class="note-header">
      <Dropdown style="margin-left: 20px">
        <a href="javascript:void(0)">
          {{ currentNotebook.name }}
          <Icon type="arrow-down-b"></Icon>
        </a>
        <DropdownMenu slot="list">
          <DropdownItem v-for="notebook in notebooks" :key="notebook.id">
            <span @click="doGetNote(notebook.id)">{{ notebook.name }}</span>
          </DropdownItem>
          <DropdownItem>
            <span @click="toTrash">废纸篓</span>
          </DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <Button @click="addNoteModal = true" class="add-note-btn" type="ghost" size="small">添加笔记</Button>

      <Modal v-model="addNoteModal" title="输入笔记标题" ref="addNewNoteModalRef">
        <Form ref="addNewNoteForm" :model="newNote" :rules="addNewNoteRule" inline>
          <FormItem prop="title" class="input-line">
            <Input type="text" v-model="newNote.title" placeholder="输入笔记标题">
              <Icon type="ios-paper" slot="prepend"></Icon>
            </Input>
          </FormItem>
        </Form>
        <div slot="footer">
          <i-button type="primary" size="large" @click="addNewNoteOk('addNewNoteForm')">提交</i-button>
          <i-button type="error" size="large" @click="addNewNoteCancel('addNewNoteForm')">取消</i-button>
        </div>
      </Modal>

    </div>
    <div class="note-tab">
      <div class="update-time-tab">更新时间</div>
      <div class="title-tab">标题</div>
    </div>
    <ul class="note-list">
      <li @click="doRouterNoteCurrentNotebook(currentNotebook.id, note.id, index)" :class="{ 'note-item-active': index === liIndex }" class="note-item" v-for="(note, index) in allNotes" :key="note.id">
        <Icon type="ios-paper" slot="prepend"></Icon>
        <div class="note-update-time">{{ _formatDate(note.modifiedTime) }}</div>
        <div class="note-title">{{ note.title }}</div>
      </li>
    </ul>
  </div>
</template>

<script>
  import {friendlyDate} from '../common/js/date.js'
  import {mapState} from 'vuex'

  export default {
    name: 'NoteSiderbar',
    created() {
      // 清空笔记列表
      this.$store.commit('setAllNotes', []);
      this._getNotebooks()
    },
    data() {
      return {
        notebooks: [],
        notes: [],
        currentNotebook: {},
        currentNote: {},
        selectTags: [],
        liIndex: -1,
        addNoteModal: false,
        newNote: {
          noteBookId: '',
          title: ''
        },

        addNewNoteRule: {
          title: [{
            required: true,
            message: '标题不能为空',
            trigger: 'blur'
          }, {
            type: 'string',
            min: 1,
            max: 32,
            message: ' 长度应在1-32之间',
            trigger: 'blur'
          }
          ],
        },
      }
    },
    computed: {
      ...mapState([
        'allNotes'
      ])
    },
    methods: {
      toTrash() {
        this.$router.push('/trash');
      },
      addNewNoteOk(model) {
        this.newNote.noteBookId = (this.currentNotebook) ? this.currentNotebook.id : this.$route.query.notebookId;
        // 设置参数
        this.$refs[model].validate(valid => {
          if (valid) {
            this.postJSON(this.$urlApi.SAVE_NOTE, this.newNote).then(res => {
              console.log(res);
              this.$refs[model].resetFields();
              this.addNoteModal = false;
              this._getNote(this.newNote.noteBookId);
            }).catch(err => {
              console.log(err);
            });
          } else {
            return false;
          }
        });
      },
      addNewNoteCancel(model) {
        this.$refs[model].resetFields();
        this.addNoteModal = false;
      },
      doRouterNoteCurrentNotebook(notebookId, noteId, index) {
        this.liIndex = index;
        this.$store.commit('setNotebookId', notebookId);
        this.$store.commit('setNoteId', noteId);
        this.currentNote = this.notes.find(note => note.id === this.$store.state.noteId) || {};
        this.$store.commit('setCurrentNote', this.currentNote);
        this.$store.commit('setSelectTags', this.currentNote.tags.map(tag => tag.id));
        this.$router.push(`/note?noteId=${noteId}&notebookId=${notebookId}`);
      },
      doGetNote(notebookId) {
        this._getNote(notebookId);
        this.currentNotebook = this.notebooks.find(notebook => notebook.id === notebookId);
        this.$store.commit('setCurrentNote', {});
        this.$router.push(`/note?notebookId=${notebookId}`);
      },

      _getNote(notebookId) {
        let param = {'noteBook.id' : notebookId};
        this.postQuery(this.$urlApi.QUERY_NOTE_LIST, param).then(res => {
          this.notes = res.data;
          if (this.notes.length > 0) {
            this.notes.sort();
            this.$store.commit('setAllNotes', this.notes);
          } else {
            this.$Message.info('该笔记本下暂无笔记');
            this.$store.commit('setAllNotes', []);
          }
        }).catch(err => {
          console.log(err);
        })
      },

      _getNotebooks() {
        this.postJSON(this.$urlApi.QUERY_BOOK_LIST).then(res => {
          this.notebooks = res.data;
          if (this.notebooks && this.notebooks.length > 0) {
            this.notebooks.sort().reverse();
            if (this.$route.query.notebookId) {
              this.currentNotebook = this.notebooks.find(notebook => notebook.id === this.$route.query.notebookId);
              this._getNote(this.currentNotebook.id);
            } else {
              this.currentNotebook = this.notebooks[0];
              this._getNote(this.currentNotebook.id);
            }
          }
        }).catch(err => {
          console.log(err);
        });

      },
      _formatDate(dateStr) {
        return friendlyDate(dateStr)
      }
    },
  }
</script>

<style lang="stylus" scoped>
  @import '../common/stylus/variables.styl';
  @import '../common/stylus/styles.styl';
  .note-sidebar
    width 300px
    max-height 100%
    overflow auto
    background-color $notebook-bg
    margin-left 100px
    border-right 1px solid $line-color
    .note-header
      text-align center
      padding 15px 0
      border-bottom 1px solid $line-color
      position relative
      .add-note-btn
        position absolute
        right 5px
        top 12px
    .note-tab
      display flex
      font-size 14px
      border-bottom 1px solid $line-color
      .update-time-tab, .title-tab
        padding 10px
        flex 1
      .update-time-tab
        border-right 1px solid $line-color
    .note-list
      font-size 13px
      .note-item
        display flex
        padding 10px
        border-bottom 1px solid $line-color
        cursor pointer
        transition all .3s
        &.note-item-active
          background-color $theme-color
          color #fff
        &:hover
          background-color $theme-color
          color #fff
        .note-update-time, .note-title
          flex 1
        .note-title
          padding-left 20px

  .input-line
    width 100%
    margin-bottom 10px
</style>
